﻿using System.Windows;
using System.Windows.Controls;

namespace Moonwish.Silverlight.Controls
{
    /// <summary>
    /// 具有查找TreeViewItem功能的树节点类，来自Microsoft.silverlight.net,by zhlin 2011-07-04。
    /// </summary>
    public class SmartTreeViewItem : TreeViewItem
    {
        public SmartTreeViewItem()
        {
            this.Expanded += new RoutedEventHandler(TreeViewItemExtended_Expanded);
            this.Collapsed += new RoutedEventHandler(TreeViewItemExtended_Collapsed);
        }
        void TreeViewItemExtended_Collapsed(object sender, RoutedEventArgs e)
        {
            ParentTreeView.InvokeContainerCollapsed(sender, e);
        }

        void TreeViewItemExtended_Expanded(object sender, RoutedEventArgs e)
        {
            ParentTreeView.InvokeContainerExpanded(sender, e);
        }

        protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems[0] is SmartTreeViewItem)
            {
                var newItem = (SmartTreeViewItem)e.NewItems[0];
                newItem.ParentTreeView = ParentTreeView;
                newItem.ParentTreeViewItem = this;
            }
            base.OnItemsChanged(e);
        }

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is DropTreeView;
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new SmartTreeViewItem();
        }

        public SmartTreeView ParentTreeView
        {
            get;
            set;
        }

        public SmartTreeViewItem ParentTreeViewItem { internal set; get; }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            var treeViewItem = (SmartTreeViewItem)element;
            treeViewItem.ParentTreeView = this.ParentTreeView;
            treeViewItem.ParentTreeViewItem = this;
            base.PrepareContainerForItemOverride(element, item);

            ParentTreeView.InvokeContainerPrepared(treeViewItem, item);
        }
    }
}
